<script setup lang="ts">
import { getFileListApi } from "@/api/share/index"
import { FilesData } from "@/api/share/types"
import { ContentWrapNoHeaderLine } from '@/components/ContentWrap'
import { Table } from '@/components/Table'
import { useTable } from "@/hooks/web/useTable"
import { Pagination, TableColumn } from "@/types/table"
import { propTypes } from '@/utils/propTypes'
import {
  ElAside,
  ElButton,
  ElContainer,
  ElDivider,
  ElFormItem,
  ElInput,
  ElMain,
  ElSpace,
  ElTree
} from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { h, reactive, ref, watch } from 'vue'

const props = defineProps({
  companyId: propTypes.string.def(''),
  userId: propTypes.string.def('')
})

const emit = defineEmits(['selected'])

const queryModel = reactive<Recordable>({
  company_id: props.companyId,
  user_id: props.userId,
  parent_id: '0',
  find_key: '',
  file_name: '',
  file_id: '0',
  up_id: '0',
})

const columns = reactive<TableColumn[]>([
  {
    field: 'file_name',
    label: '虚拟盘文件名',
    search: false,
    visible: true,
    className: ''
  }, {
    field: 'file_path',
    label: '文件路径',
    search: false,
    visible: true,
    className: ''
  }, {
    field: 'file_type',
    label: '文件类型',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'length',
    label: '文件长度（字节）',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'action',
    label: '操作',
    visible: true,
    className: ''
  }
])

const { register, tableObject, methods } = useTable<FilesData>({
  getListApi: getFileListApi,
  response: {
    list: 'list',
    total: 'total'
  }
})
const paginationObj = ref<Pagination>()
watch(() => tableObject.total,
  (val) => {
    if (val > 0) {
      paginationObj.value = {
        total: tableObject.total
      }
    } else {
      paginationObj.value = undefined
    }
  })
const { setSearchParams } = methods

const cache = ref({});


const spacer = h(ElDivider, { direction: 'vertical' })

const handleQuery = () => {
  setSearchParams({ ...queryModel })
  cache.value[queryModel.parent_id + queryModel.find_key] = tableObject.tableList;
}

handleQuery()

const selectedCount = ref(0)
const multipleSelection = ref<FilesData[]>([])
const handleSelectionChange = (val: FilesData[]) => {
  multipleSelection.value = val
  selectedCount.value = val?.length || 0
}

const handleSelectButton = (row: FilesData) => {
  emit("selected", row);
}

const treeData: FilesData[] = [];
const defaultProps = {
  children: 'children',
  label: 'file_name',
}

const loadNode = (node: Node, resolve: (data: FilesData[]) => void) => {
  if (node.level === 0) {
    return resolve([{ file_id: 0, file_name: '根目录', file_path: '', file_type: '', parent_id: '', length: 0 }])
  }
  getFileList(node.data.file_id);
}

const getFileList = (parent_id) => {
  let data = cache.value[parent_id + queryModel.find_key]
  if (data) {
    return data.filter(d => { return d.file_type == '1' });
  } else {
    const queryParams = { ...queryModel };
    queryParams.parent_id = parent_id;
    getFileListApi({ ...queryParams }).then(res => {
      cache.value[parent_id + queryModel.find_key] = res.data.list
      return res.data.list.filter(d => { return d.file_type == '1' });
    });
  }
}

const fileType = {
  "0": "文件",
  "1": "文件夹"
}

const handleTreeNodeClick = (data: FilesData) => {
  queryModel.parent_id = data.file_id;
  handleQuery();
}


</script>

<template>
  <el-container>
    <el-aside width="200px">
      <el-tree :data="treeData" :load="loadNode" lazy :props="defaultProps" @node-click="handleTreeNodeClick" />
    </el-aside>
    <el-main>
      <ContentWrapNoHeaderLine title="">
        <el-form :inline="true" ref="queryFormRef" :model="queryModel">
          <el-form-item>
            <el-space direction="horizontal" :size="0">
              <el-input v-model="queryModel.company_id" placeholder="" readonly/>
              <el-input v-model="queryModel.user_id" placeholder="" readonly/>
              <el-input v-model="queryModel.find_key" placeholder="请输入关键字">
                <template #append>
                  <el-button class="query-button" type="primary" @click="handleQuery">查询</el-button>
                </template>
              </el-input>
            </el-space>
          </el-form-item>
        </el-form>
        <div class="">
          <Table border v-model:pageSize="tableObject.page_size" v-model:currentPage="tableObject.page_index"
            :columns="columns" :data="tableObject.tableList" :loading="tableObject.loading" :pagination="paginationObj"
            @register="register" @select="handleSelectionChange" @select-all="handleSelectionChange">
            <template #file_type="{ row }">
              {{ fileType[row.fileType] }}
            </template>
            <template #action="{ row }">
              <el-space :size="6" :spacer="spacer">
                <ElButton type="primary" link @click="handleSelectButton(row)">
                  选择
                </ElButton>
              </el-space>
            </template>
          </Table>
        </div>
      </ContentWrapNoHeaderLine>
    </el-main>
  </el-container>
</template>
